package services

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"sync"
)

// FieldMappingService 字段映射服务
type FieldMappingService struct {
	mappingPath string
	mappings    map[string]FieldMapping // templateID -> FieldMapping
	mu          sync.RWMutex
}

// FieldMapping 字段映射配置
type FieldMapping struct {
	TemplateID string            `json:"templateId"`
	Rules      []MappingRule     `json:"rules"`
}

// MappingRule 映射规则
type MappingRule struct {
	OCRField    string `json:"ocrField"`    // OCR 识别出的字段名
	TemplateVar string `json:"templateVar"` // 模板中的变量名
}

// NewFieldMappingService 创建字段映射服务
func NewFieldMappingService() *FieldMappingService {
	homeDir, _ := os.UserHomeDir()
	mappingDir := filepath.Join(homeDir, ".batch-doc-generator", "mappings")
	os.MkdirAll(mappingDir, 0755)
	
	mappingPath := filepath.Join(mappingDir, "field_mappings.json")
	
	return &FieldMappingService{
		mappingPath: mappingPath,
		mappings:    make(map[string]FieldMapping),
	}
}

// LoadMappings 加载所有映射
func (s *FieldMappingService) LoadMappings() (map[string]FieldMapping, error) {
	s.mu.RLock()
	if len(s.mappings) > 0 {
		s.mu.RUnlock()
		return s.mappings, nil
	}
	s.mu.RUnlock()

	s.mu.Lock()
	defer s.mu.Unlock()

	// 双重检查
	if len(s.mappings) > 0 {
		return s.mappings, nil
	}

	// 读取文件
	if _, err := os.Stat(s.mappingPath); os.IsNotExist(err) {
		s.mappings = make(map[string]FieldMapping)
		return s.mappings, nil
	}

	data, err := os.ReadFile(s.mappingPath)
	if err != nil {
		return nil, err
	}

	var mappingsList []FieldMapping
	err = json.Unmarshal(data, &mappingsList)
	if err != nil {
		return nil, err
	}

	s.mappings = make(map[string]FieldMapping)
	for _, mapping := range mappingsList {
		s.mappings[mapping.TemplateID] = mapping
	}

	return s.mappings, nil
}

// SaveMappings 保存所有映射
func (s *FieldMappingService) SaveMappings() error {
	s.mu.Lock()
	defer s.mu.Unlock()

	var mappingsList []FieldMapping
	for _, mapping := range s.mappings {
		mappingsList = append(mappingsList, mapping)
	}

	data, err := json.MarshalIndent(mappingsList, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(s.mappingPath, data, 0644)
}

// GetMapping 获取模板的映射规则
func (s *FieldMappingService) GetMapping(templateID string) (*FieldMapping, error) {
	mappings, err := s.LoadMappings()
	if err != nil {
		return nil, err
	}

	mapping, exists := mappings[templateID]
	if !exists {
		return &FieldMapping{
			TemplateID: templateID,
			Rules:      []MappingRule{},
		}, nil
	}

	return &mapping, nil
}

// SaveMapping 保存模板的映射规则
func (s *FieldMappingService) SaveMapping(mapping FieldMapping) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.mappings[mapping.TemplateID] = mapping
	return s.SaveMappings()
}

// ApplyMapping 应用映射规则，将 OCR 结果转换为模板变量
func (s *FieldMappingService) ApplyMapping(templateID string, ocrData map[string]interface{}) (map[string]string, error) {
	mapping, err := s.GetMapping(templateID)
	if err != nil {
		return nil, err
	}

	result := make(map[string]string)
	
	// 应用映射规则
	for _, rule := range mapping.Rules {
		if value, exists := ocrData[rule.OCRField]; exists {
			// 转换为字符串
			result[rule.TemplateVar] = fmt.Sprintf("%v", value)
		}
	}

	return result, nil
}

